import { FC, useState } from 'react';
import Sform from './src/form';
import { message, Table, Image, Button } from 'antd';
import { ColumnsType } from 'antd/es/table';
import TableAction, {
  MenuItem,
} from '@/components/commonComponent/tableAction/tableAction';
import useRequest from '@ahooksjs/use-request';
import { splitSearchParams } from '@/utils/common';
import { getpictures, delete_picture_id_api, getDatasets } from '@/api/sr-stms';
import { AlgorithmItem } from '.';
import AddFilesModal from './src/addFilesModal';
import { useToggle } from 'ahooks';

interface Iprops {
  selectedAlgorithm: AlgorithmItem | null;
}

const Content: FC<Iprops> = (props) => {
  const { selectedAlgorithm } = props;
  const [searchParams, setSearchParams] = useState<SearchParam[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [addFilesModalVis, { toggle: toggleAddFilesModalVis }] =
    useToggle(false);

  const { tableProps, refresh } = useRequest(
    ({ current, pageSize }) =>
      getpictures({
        page: current,
        size: pageSize,
        search_params: [
          ...searchParams,
          {
            field_name: 'algorithm_name',
            operator: 'eq',
            value: selectedAlgorithm?.name,
          },
        ],
      }),
    {
      ready: !!selectedAlgorithm,
      paginated: true,
      refreshDeps: [searchParams, selectedAlgorithm],
      formatResult: (res) => ({
        list: res.data.list,
        total: res.data.total_elements,
      }),
    },
  );

  const { data: datasetList } = useRequest(
    () =>
      getDatasets({
        size: 10,
        page: 1,
        search_params: [
          {
            field_name: 'algorithm_name',
            operator: 'eq',
            value: selectedAlgorithm?.name,
          },
        ],
      }),
    {
      ready: !!selectedAlgorithm,
      refreshDeps: [selectedAlgorithm],
      formatResult: (res) => {
        return res.data.list;
      },
    },
  );

  const columns: ColumnsType<any> = [
    { title: '图片名称', dataIndex: 'file_name' },
    {
      title: '图片',
      dataIndex: 'id',
      render: (id) => (
        <Image
          width={200}
          src={window.config.SERVER_HOST + `/file/download/${id}`}
        ></Image>
      ),
    },
    { title: '模型标识名称', dataIndex: 'algorithm_name' },

    {
      title: '操作',
      render: (text, record) => {
        return (
          <TableAction
            record={record}
            menuList={menuList}
            // onEditClick={handleEditClick}
            showEdit={false}
          ></TableAction>
        );
      },
      // render: (text, record) => <span onClick={() => handleDelClick(record.id)}>删除</span>
    },
  ];

  const menuList: MenuItem<any>[] = [
    { name: '删除', fn: (record) => handleDelClick(record.id) },
  ];

  const handleDelClick = async (id: string) => {
    //调用删除接口
    await delete_picture_id_api(id)();
    message.success('删除成功！');
    refresh();
  };

  /** 表单查询回调 */
  const formSearch = (vals: any) => {
    setSearchParams(splitSearchParams(vals));
  };

  /** 新增、编辑成功回调 */
  const drawerCallback = () => {
    refresh();
  };

  return (
    <div style={{ padding: 20, background: '#fff' }}>
      <AddFilesModal
        visible={addFilesModalVis}
        onCancel={() => {
          toggleAddFilesModalVis(false);
        }}
        callback={() => {
          setSelectedRowKeys([]);
        }}
        datasetList={datasetList}
        fileIds={selectedRowKeys}
      ></AddFilesModal>
      <Sform formSearch={formSearch}></Sform>
      <div className="action-add-row">
        <Button
          type="primary"
          disabled={selectedRowKeys.length === 0}
          onClick={() => {
            toggleAddFilesModalVis(true);
          }}
        >
          添加至数据集 ({selectedRowKeys.length})
        </Button>
      </div>
      <Table
        {...tableProps}
        pagination={{
          ...tableProps.pagination,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `总共 ${total} 条`,
        }}
        columns={columns}
        rowKey={(record) => record.id}
        bordered
        rowSelection={{
          selectedRowKeys,
          onChange: (rowKeys) => {
            setSelectedRowKeys(rowKeys);
          },
        }}
      ></Table>
    </div>
  );
};

export default Content;
